package com.itgy.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.itgy.apiclientsdk.model.User;
import com.itgy.apiclientsdk.util.SignUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ApiClient {

    private String secretKey;
    private String accessKey;
    private static final String HOST_GATEWAY = "http://127.0.0.1:8090";

    public ApiClient(String secretKey, String accessKey) {
        this.secretKey = secretKey;
        this.accessKey = accessKey;
    }

    public ApiClient() {
    }

    public String getNameByGet(String name)
    {

       //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result= HttpUtil.get(HOST_GATEWAY+"/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNamePost(String name)
    {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result= HttpUtil.post(HOST_GATEWAY+"/api/name/", paramMap);
        System.out.println(result);
        return result;
    }
    private Map<String,String> getHeaders(String body)
    {
        Map<String,String> map = new HashMap<>();
   //     map.put("secretKey",secretKey);
        map.put("accessKey",accessKey);    //不要传递给前端
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("body",body);
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        map.put("sign", SignUtil.getSign(body,secretKey));
        return map;
    }


    public String getUserNamePost(User user)
    {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse response = HttpRequest.post(HOST_GATEWAY+"/api/name/json")
                .charset(StandardCharsets.UTF_8)
                .addHeaders(getHeaders(json))
                .body(json)
                .execute();

        System.out.println(response.getStatus());
        System.out.println(response.body());
        return response.body();
    }

}
